import React, { PureComponent } from "react";
import { connect } from "dva";
import dynamic from "umi/dynamic";
import {Modal,Form,Table, message} from "antd";
import {getUuid, openNotificationWithIcon} from "utils/comm";
import Columns from "./components/eventColumns";
import SearchForm from "./components/search.jsx";
import styles from "./components/eventComponents.less";



const EventCompensate = dynamic({ loader: async () => {
  return import("./components/eventEdit.jsx");
},
});
@connect(({ loading }) => ({
  loading,
}))
class eventConfigure extends PureComponent {
  constructor(props) {
  super(props);
  this.openNotificationWithIcon = openNotificationWithIcon.bind(this);
  this.state = {
    eventCompensateVisible: false,
    eventCompensateData: [], // 存放弹框的数据
    eventData:[],   // 存放所有节点的事件数据
    page: {
      pageNum: 1,
      pageSize: 6,
    },
    totalCount:0,
    eventList:[{name:"流程前置",value:"ACTIVITY_STARTED"},
    {name:"流程后置",value:"ACTIVITY_COMPLETED"}],
  };
  this.baseQueryParam = {
    modelId: "",
    modelKey: "",
    modelName: "",
    nodeCode: "",
    nodeName: "",
    name: "",  // 事件名称
    eventType :"", // 流程前置 流程后置
    callMethod:"", // 同步 异步
  };
  this.queryParams = this.baseQueryParam;
 }

 componentDidMount() {
  this.setEventsToTemp();
  this.initData();
  // this.initModelDetail();

}

  handleReset = () => {
    // eslint-disable-next-line no-unused-vars
    const { eventCompensateVisible,eventCompensateData,eventData } = this.state;
    this.formRef.resetFields();
    this.setState({eventData:[],eventCompensateVisible: false,eventCompensateData: []});
  };

  // 搜索
  handleSearch = () => {
    const { page } = this.state;
    this.setState({ page: { ...page, pageNum: 1 } }, () => {
      this.initData();
    });
  };

  // 获取查询参数
  getQueryParam = () => {
    const {
      page: { pageNum, pageSize },
    } = this.state;
    return { ...this.queryParams, pageNum, pageSize };
  };

  handlePageChange = ({ current: pageNum, pageSize }) => {
    this.setState({ page: { pageNum, pageSize } }, () => {
      this.initData();
    });
  };

  // 查询条件改变
  handleParamsChange = (item = {}) => {
    this.queryParams = { ...this.queryParams, ...item }
  }

  initData = () =>{
    // eslint-disable-next-line no-unused-vars
    const { dispatch,eventData } = this.props;
    const params = this.getQueryParam();
    dispatch({
      type:"flowEvent/getEventsList",
      payload:params,
    }).then((res)=>{
      if(res.errCode === 0){
        this.setState({eventData:res.datas,totalCount:res.totalCount})
      }
    })
  }

 // 触发查询
  initData1 = () => {
    // eslint-disable-next-line no-unused-vars
    const { dispatch,eventData } = this.props;
    const params = this.getQueryParam();

     
    dispatch({
      type: "flowEvent/getListData",
      payload: params, 
    }).then((res) => {
      const EventList=[];
      const total=res.totalCount;
      if (res.errCode === 0){
        const modelList=res.datas;
        if(modelList){
          let i=0;
          for(i=0;i<modelList.length;i+=1){
            const temp={};
            temp.id=i+1;
            temp.modelId=modelList[i].modelId;
            temp.modelKey=modelList[i].modelKey;
            temp.modelName=modelList[i].modelName;
            const query={modelId:modelList[i].modelId}
            const childrenData=this.handleSubmit(query,i+1);
            if(childrenData){
              temp.children=childrenData;
            }
            EventList.push(temp);
          }
        } 

      }
      this.setState({eventData:EventList,totalCount:total})
    })
    };

  getEditThis = _this => {
    this.flowEditRef = _this;
  };

  setEventsToTemp=()=>{
    const { dispatch} = this.props;
    dispatch({
      type:"flowEvent/setEventsList",
      payload:null,
    }).then((res)=>{
      if(res.errCode === 0){
        // this.openNotificationWithIcon("success", "", `模型事件刷新成功`);
        message.success("模型事件刷新成功",1);
      }
    })
  }

  // // 通过Id获取信息
  // initModelDetail = () => {
  //   // reset
  //   const { searchData } = this.state;
  //   const {
  //     location: {
  //       query: { modelid = "", modelId: _mId = "" },
  //       state: lstate,
  //     },
  //     dispatch,
  //   } = this.props;
  //   const mId = modelid || _mId;
  //   if(mId.length>0){
  //     this.setState({searchData:{modelId:mId}});
  //     const query={modelId:mId}
  //     this.handleSumbit(query);
  //   }
  //   else{
  //    message.info("请输入modelId");
  //   }
    
  // }

  handleEventCompensateVisible = () => {
  const { eventCompensateVisible } = this.state;
   this.setState( {eventCompensateVisible :!eventCompensateVisible});
 
  };

  handleSubmit = (query,current) => {
    const { dispatch } = this.props;
    const eventDataTemp=[]; 
    dispatch({
        type: "flowEvent/getModelDetail",
        payload:query,
      }).then((res) => {
        if (res.errCode === 0) {
           const node=res.datas.modelJson.nodes;
           const len=node.length;
           let j=0;
           let flag=100*current;
           let k=0;
           for(j=0;j<len;j+=1){
            const eventconfigs=node[j].model.properties.eventConfig;
            if(eventconfigs){
              for(k=0;k<eventconfigs.length;k+=1){
                const temp={};
                temp.id=flag;
                temp.modelKey=res.datas.key;
                temp.modelId=res.datas.modelId;
                temp.modelName=res.datas.name;
                temp.nodeName=node[j].model.properties.name;
                temp.nodeCode=node[j].model.properties.overrideid;
                temp.callMethod=eventconfigs[k].callMethod;
                temp.eventType=eventconfigs[k].eventType;
                temp.eventName=eventconfigs[k].name;
                temp.url=eventconfigs[k].config.url;
                temp.requestBody=eventconfigs[k].requestBody;
                temp.desc=eventconfigs[k].desc;
                eventDataTemp.push(temp);
                flag+=1;
              }
            }
          }
        }
    })
   // console.log(eventDataTemp.length);
    return eventDataTemp;
  };

  handleEdit = (record) => {
     this.handleEventCompensateVisible();
     const { eventCompensateData,eventList } = this.state; // eslint-disable-line no-unused-vars
     this.setState({eventCompensateData:[{
      key: getUuid(),
      name: record.name,
      configContent: record.configContent,
      callMethod: record.callMethod,
      requestBody: record.requestBody,
      eventType:  record.eventType,
      desc: record.desc,
      modelId: record.modelId,
      nodeCode: record.nodeCode,
     }]});
     if(record.eventType){
        if(record.eventType.indexOf("TASK")!==-1){
          this.setState({eventList:[{name:"流程前置",value:"TASK_CREATED"},
          {name:"流程后置",value:"TASK_COMPLETED"}]})
        }
     }
  }

  testEvent = (form) => {
    const { dispatch } = this.props;
    this.handleEventCompensateVisible();
    dispatch({
      type: "flowEvent/testEvent",
      payload: {
        requestJsonParams: form.config,
        requestUrl: form.requestBody,
      },
    }).then((res) => {
      const result=res.datas;
      const errmessage=res.errMsg;
      let resultTitle;
      if (res.errCode === 0) {
        resultTitle="测试成功";
      }
      else{
        resultTitle="测试失败";
      }
      Modal.confirm({
        width: "500px",
        height: "500px",
        centered:true,
        title: resultTitle,
        content:(
          <Form>
            <Form.Item label="接口返回message">
              <textarea rows="1" cols="50" value={errmessage} readOnly />
            </Form.Item>
            <Form.Item label="接口返回datas">
              <textarea rows="2" cols="50" value={JSON.stringify(result)} readOnly />
            </Form.Item>
          </Form>),
        cancelText:"取消",
        okText:"确认",
      });

    });
  };

  render() {
    const {
      eventCompensateVisible,
      eventCompensateData,
      eventData,
      searchData,   // eslint-disable-line no-unused-vars
      page: { pageNum, pageSize },
      totalCount,
      eventList,
    } = this.state;
    const columns = Columns(this.handleEdit);
    const {dispatch} = this.props;
    return (
      <div className={styles.root}>
        <div className={styles.listform}>
          <div className={styles.search}>
            <SearchForm
              onRef={(f) => {
                this.formRef = f;
              }}
              handleSubmit={this.handleSubmit}
              handleReset={this.handleReset}
              handleSearch={this.handleSearch}
              handleParamsChange={this.handleParamsChange}
              setEventsToTemp={this.setEventsToTemp}
            />
          </div>
        </div>
        <div className={styles.content}>
          <Table
            rowKey="id"
            dataSource={eventData}
            columns={columns}
            bordered
            className={styles.spacing}
            onChange={this.handlePageChange}
            pagination={{
              showQuickJumper: true,
              showSizeChanger: true,
              pageSizeOptions: ["10", "20", "30"],
              current: pageNum,
              pageSize,
              total: totalCount,
            }}
          />
          <EventCompensate
            visible={eventCompensateVisible}
            handleEventCompensateVisible={this.handleEventCompensateVisible}
            eventCompensateData={eventCompensateData}
            testEvent={this.testEvent}
            eventList={eventList}
            dispatch={dispatch}
          />
        </div>
      </div>
    );
  }
}
export default eventConfigure;

